import CodoBase from "../../../lib/CodoBase";
import CodoError from "../../../lib/CodoError";
import { Wechat } from "../wechat";

export default class CodoWechatMpMessage extends CodoBase {
	/** 小程序发送订阅消息 */
	async sendMessage(msg: Wechat.mp.request.sendSubscribeMessage, access_token?: string) {
		const token = access_token || this.app.codo.wechat.mp.accessToken.getCurrentContextCacheAccessToken();
		const url = `https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=${token}`;

		const res = await this.app.curl<Wechat.ICommonRespnose>(url, {
			method: "POST",
			dataType: "json",
			data: msg,
			contentType: "json",
		});
		if (res.data.errcode) {
			throw new CodoError(`小程序发送消息失败 %s %s`, res.data.errcode, res.data.errmsg);
		}
		return res.data;
	}

	/** 获取账号下已有的模板列表 */
	async getMessageTemplateList(access_token?: string) {
		const token = access_token || this.app.codo.wechat.mp.accessToken.getCurrentContextCacheAccessToken();
		const url = `https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate?access_token=${token}`;

		const res = await this.app.curl<Wechat.ICommonRespnose & Wechat.mp.response.MessageTemplateListObject[]>(url, {
			method: "GET",
			dataType: "json",
			contentType: "json",
		});
		if (res.data.errcode) {
			throw new CodoError(`小程序获取账号下消息模板列表失败 %s %s`, res.data.errcode, res.data.errmsg);
		}
		return res.data;
	}
}
